package com.hps.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hps.demo.dto.OrderInitDTO;
import com.hps.demo.entity.Good;
import com.hps.demo.entity.Order;
import com.hps.demo.entity.User;
import com.hps.demo.mapper.OrderMapper;
import com.hps.demo.msg.KafkaSender;
import com.hps.demo.service.IGoodService;
import com.hps.demo.service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hps.demo.service.IUserService;
import com.hps.demo.vo.OrderDetailVO;
import com.hps.demo.vo.OrderInfoVO;
import com.hps.demo.vo.PageVO;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author heps
 * @since 2020-10-27
 */
@Slf4j
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

  @Resource
  private IGoodService goodService;

  @Resource
  private IUserService userService;

  @Resource
  private KafkaSender kafkaSender;

  @Async("bizExecutor")
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void initData(OrderInitDTO orderInitDTO) {
    log.info("start init order: {}", orderInitDTO.getCount());
//    List<Order> orderList = new ArrayList<>();
    Random random = new Random(System.currentTimeMillis());
    for (int i = 0; i < orderInitDTO.getCount(); i++) {
      Order order = new Order();
      order.setGoodId((long) (1 + random.nextInt(orderInitDTO.getMaxGoodId())));
      order.setUserId((long) (1 + random.nextInt(orderInitDTO.getMaxUserId())));

      kafkaSender.send("orderTopic", order);
//      orderList.add(order);
//
//      if (orderList.size() > 500) {
//        super.saveBatch(orderList);
//        orderList.clear();
//      }
    }
//    if (orderList.size() > 0) {
//      super.saveBatch(orderList);
//    }
    log.info("init order success");
  }

  @Async("bizExecutor")
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void reduceNoOrderUser(OrderInitDTO orderInitDTO) {
    log.info("reduceNoOrderUser start");
    List<User> noOrderUser = userService.getNoOrderUser();
    if (CollectionUtils.isNotEmpty(noOrderUser)) {
      log.info("user count: {}", noOrderUser.size());
      List<Order> orderList = new ArrayList<>();
      Random random = new Random(System.currentTimeMillis());
      for (User user : noOrderUser) {
        Order order = new Order();
        order.setUserId(user.getId());
        order.setGoodId(1L + random.nextInt(orderInitDTO.getMaxGoodId()));

        orderList.add(order);
      }

      super.saveBatch(orderList);
    }
    log.info("reduceNoOrderUser success");
  }

  @Override
  public Page<OrderInfoVO> getOrderInfo(PageVO pageVO) {
    Page<OrderInfoVO> page = new Page<>(pageVO.getPage(), pageVO.getSize());
    return baseMapper.queryOrderByPage(page);
  }

  @Override
  public Page<OrderInfoVO> getOrderPage(PageVO pageVO) {
    Page<Order> page = new Page<>(pageVO.getPage(), pageVO.getSize());
    Page<Order> orderPage = super.page(page);

    Page<OrderInfoVO> orderInfoVOPage = new Page<>(orderPage.getCurrent(), orderPage.getSize(), orderPage.getTotal());
    if (orderPage.getRecords().size() > 0) {
      List<OrderInfoVO> orderInfoVOList = new ArrayList<>();

      List<Long> goodIdList = orderPage.getRecords()
          .stream()
          .mapToLong(Order::getGoodId)
          .boxed()
          .collect(Collectors.toList());
      List<Good> goodList = goodService.list(new LambdaQueryWrapper<Good>()
          .in(Good::getId, goodIdList)
      );
      List<Long> userIdList = orderPage.getRecords()
          .stream()
          .mapToLong(Order::getUserId)
          .boxed()
          .collect(Collectors.toList());
      List<User> userList = userService.list(new LambdaQueryWrapper<User>()
          .in(User::getId, userIdList)
      );

      for (Order order : orderPage.getRecords()) {
        OrderInfoVO orderInfoVO = new OrderInfoVO();
        orderInfoVO.setId(order.getId());
        Good good = goodList
            .stream()
            .filter(item -> Objects.equals(order.getGoodId(), item.getId()))
            .findAny()
            .orElse(null);
        if (Objects.nonNull(good)) {
          orderInfoVO.setGoodName(good.getName());
        }
        User user = userList
            .stream()
            .filter(item -> Objects.equals(order.getUserId(), item.getId()))
            .findAny()
            .orElse(null);
        if (Objects.nonNull(user)) {
          orderInfoVO.setUsername(user.getName());
        }

        orderInfoVOList.add(orderInfoVO);
      }
      orderInfoVOPage.setRecords(orderInfoVOList);
    }
    return orderInfoVOPage;
  }

  @Override
  public Page<OrderInfoVO> getOrderPageCache(PageVO pageVO) {
    Page<Order> page = new Page<>(pageVO.getPage(), pageVO.getSize());
    Page<Order> orderPage = super.page(page);

    Page<OrderInfoVO> orderInfoVOPage = new Page<>(orderPage.getCurrent(), orderPage.getSize(), orderPage.getTotal());
    if (orderPage.getRecords().size() > 0) {
      List<OrderInfoVO> orderInfoVOList = new ArrayList<>();
      for (Order order : orderPage.getRecords()) {
        OrderInfoVO orderInfoVO = new OrderInfoVO();
        orderInfoVO.setId(order.getId());
        Good good = goodService.getByIdCache(order.getGoodId());
        if (Objects.nonNull(good)) {
          orderInfoVO.setGoodName(good.getName());
        }
        User user = userService.getByIdCache(order.getUserId());
        if (Objects.nonNull(user)) {
          orderInfoVO.setUsername(user.getName());
        }

        orderInfoVOList.add(orderInfoVO);
      }
      orderInfoVOPage.setRecords(orderInfoVOList);
    }
    return orderInfoVOPage;
  }

  @Override
  public List<OrderInfoVO> getOrderInfoByUserId(Long userId) {
    return baseMapper.getOrderInfoByUserId(userId);
  }

  @Override
  public List<OrderInfoVO> getOrderInfoSingleByUserId(Long userId) {
    List<Order> orderList = super.list(new QueryWrapper<Order>()
        .lambda()
        .eq(Order::getUserId, userId)
    );
    if (CollectionUtils.isEmpty(orderList)) {
      return Collections.emptyList();
    }
    User user = userService.getById(userId);
    return orderList
        .stream()
        .map(order -> {
          OrderInfoVO vo = new OrderInfoVO();
          vo.setId(order.getId());
          Good good = goodService.getById(order.getGoodId());
          if (Objects.nonNull(good)) {
            vo.setGoodName(good.getName());
          }
          if (Objects.nonNull(user)) {
            vo.setUsername(user.getName());
          }
          return vo;
        })
        .collect(Collectors.toList());
  }

  @Override
  public List<OrderInfoVO> getOrderInfoCacheByUserId(Long userId) {
    List<Order> orderList = super.list(new QueryWrapper<Order>()
        .lambda()
        .eq(Order::getUserId, userId)
    );
    if (CollectionUtils.isEmpty(orderList)) {
      return Collections.emptyList();
    }
    User user = userService.getByIdCache(userId);
    return orderList
        .stream()
        .map(order -> {
          OrderInfoVO vo = new OrderInfoVO();
          vo.setId(order.getId());
          Good good = goodService.getByIdCache(order.getGoodId());
          if (Objects.nonNull(good)) {
            vo.setGoodName(good.getName());
          }
          if (Objects.nonNull(user)) {
            vo.setUsername(user.getName());
          }
          return vo;
        })
        .collect(Collectors.toList());
  }

  @Override
  public Page<OrderDetailVO> getOrderDetailPage(PageVO page) {
    Page<OrderDetailVO> queryPage = new Page<>(page.getPage(), page.getSize());
    return baseMapper.getOrderDetailPage(queryPage);
  }
}
